package com.taptech.doufu.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.taptech.doufu.R;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.bean.CollectUnReadBean;
import com.taptech.doufu.bean.MarketNoticeBean;
import com.taptech.doufu.bean.choice.NewUserGiftModel;
import com.taptech.doufu.bean.shelf.BookShelfBean;
import com.taptech.doufu.bean.shelf.BookShelfPopularize;
import com.taptech.doufu.bean.shelf.BookShelfPopularizeList;
import com.taptech.doufu.constant.BookshelfJumpType;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.constant.ContentType;
import com.taptech.doufu.constant.UmengEventName;
import com.taptech.doufu.event.BaseEventBusBean;
import com.taptech.doufu.event.EventBusCollectUnRead;
import com.taptech.doufu.event.EventBusConstant;
import com.taptech.doufu.event.EventBusPersonRecommend;
import com.taptech.doufu.listener.CommmonImp;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.manager.UserLogManager;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.services.CartoonServices;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.services.PersonalNoteService;
import com.taptech.doufu.services.history.ReadHistoryUtil;
import com.taptech.doufu.services.history.ReadRecord;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.ui.activity.BrowseActivity;
import com.taptech.doufu.ui.activity.CartoonScanNewActivity;
import com.taptech.doufu.ui.activity.NovelDetailsActivity;
import com.taptech.doufu.ui.activity.NovelSectionDetailsActivity;
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity;
import com.taptech.doufu.ui.adapter.BookshelfGalleryAdapter;
import com.taptech.doufu.ui.view.AutoScrollView;
import com.taptech.doufu.ui.view.choice.ChoiceTopicNewUserView;
import com.taptech.doufu.ui.view.colorful.Colorful;
import com.taptech.doufu.util.CacheUtil;
import com.taptech.doufu.util.DensityUtil;
import com.taptech.doufu.util.ScreenUtil;
import com.taptech.doufu.util.StartActivityUtil;
import com.taptech.doufu.util.StartActivityUtils;
import com.taptech.doufu.util.TMAnalysis;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.util.image.ImagePickUtil;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;
import com.taptech.doufu.weex.http.TFHttpError;
import com.taptech.doufu.weex.http.TFHttpResponse;
import com.taptech.doufu.weex.http.TFHttpUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.functions.Action1;

/**
 * Created by longsiyang on 16/4/5.
 */
public class DFBookshelfFragment extends DiaobaoBaseFragment implements View.OnClickListener, HttpResponseListener, AdapterView.OnItemClickListener {
    private RelativeLayout rl_keep;//收藏
    private RelativeLayout rl_history;//历史记录
    private RelativeLayout rl_offline;//离线
    private RelativeLayout rl_rss;//订阅
    private RelativeLayout rlHistoryView;
    private RelativeLayout rlBuyBook; //购买的书
    private RelativeLayout rlBookList; //购买的书
    private TextView tv_rss;
    //    private HorizontalRecyclerView hRecycleView;//水平滚动轴
    private Gallery gallery;
    private List<MarketNoticeBean> marketNoticeList;
    private List<BookShelfPopularize> popularizeList = new ArrayList<>();
    private AutoScrollView autoScrollView;
    private TextView tvUnRead;
    private View layStatusHeight;
    private TextView tvLeftTag;
    private LinearLayout rl_topHistoy;
    //    private HoriRecyAda ada;
    private BookshelfGalleryAdapter adapter;
    private Colorful mColorful;
    View rootView;
    private View iconImag[] = new View[6];
    private LinearLayout dfbook_notice_layout;
    private RefreshLayout refreshLayout;
    private RelativeLayout layGift;
    private ScrollView mScrollView;
    private View laySign;
    private ImageView ivSign;
    private TextView tvSign;
    private boolean isSign = false;
    public DFBookshelfFragment() {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateBookShelf(BaseEventBusBean event) {
        if (event != null&& event.getTag() !=null && event.getTag().equals(EventBusConstant.TAG_BOOK_SHELF)) {
            Observable.timer(1,TimeUnit.SECONDS)
                    .compose(RxJavaHelper.<Long>observeOnMainThread(getActivity()))
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            loadHistoryRecord();
                        }
                    });

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void reload(EventBusPersonRecommend eventBusPersonRecommend) {
        if (eventBusPersonRecommend != null && EventBusPersonRecommend.tag.equals(eventBusPersonRecommend.getTag())) {
            getDataFromNet();
        }
    }




    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCollectCountUnRead(EventBusCollectUnRead event) {
        if (event != null && !TextUtils.isEmpty(event.getTag()) && event.getTag().equals(EventBusCollectUnRead.TAG_BOOK_SHELF)) {
            if (event.isShow()) {
                tvUnRead.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(event.getShowText())) {
                    tvUnRead.setText(event.getShowText());
                }else{
                    tvUnRead.setText("1");
                }
            }else{
                tvUnRead.setVisibility(View.GONE);
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_dfbookshelf, null);
            findViews(rootView);
            loadCacheDate();
            getDataFromNet();
        }

        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        setupColorful();
    }
    private void loadCacheDate() {
        if (AccountService.getInstance().isLogin()) {
            try {
                JSONObject cacheData = CacheUtil.readJsonDataFromCache(new File(CommmonImp.Home_bookshelf));
                BookShelfBean bean = new BookShelfBean();
                bean.setCount("0");
                if ((cacheData.has("count"))) {
                    bean.setCount(cacheData.getString("count"));
                }
                setData(bean);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            tv_rss.setVisibility(View.INVISIBLE);
        }

        try {
            JSONObject cacheData = CacheUtil.readJsonDataFromCache(new File(CommmonImp.Home_bookshelf_market));
            marketNoticeList = com.alibaba.fastjson.JSONArray.parseArray(cacheData.getJSONArray("list").toString(), MarketNoticeBean.class);
            autoScrollView.updateScroolNotices(tvLeftTag, marketNoticeList);
            if (marketNoticeList != null && marketNoticeList.size() > 0) {
                dfbook_notice_layout.setVisibility(View.VISIBLE);
            } else {
                dfbook_notice_layout.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * provider the view finds method
     */
    private void findViews(View rootView) {
        layStatusHeight = rootView.findViewById(R.id.layStatusHeight);
        layStatusHeight.setVisibility(View.VISIBLE);
        //设置状态栏高度
        RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, ScreenUtil.getStatusHeight(getActivity()));
        layStatusHeight.setLayoutParams(params2);
        tvUnRead = (TextView) rootView.findViewById(R.id.tvUnRead);
        autoScrollView = (AutoScrollView) rootView.findViewById(R.id.auto_homebookself);
        tvLeftTag = (TextView) rootView.findViewById(R.id.tv_home_type);
        rl_topHistoy = (LinearLayout) rootView.findViewById(R.id.rela_bookshelf_history);
        rl_keep = (RelativeLayout) rootView.findViewById(R.id.rela_homebookshelf_keep);
        rl_keep.setOnClickListener(this);
        rl_history = (RelativeLayout) rootView.findViewById(R.id.rela_homebookshelf_history);
        rl_history.setOnClickListener(this);
        rlBookList = (RelativeLayout) rootView.findViewById(R.id.rlBookList);
        rlBookList.setOnClickListener(this);
        rlBuyBook = (RelativeLayout) rootView.findViewById(R.id.rlBuyBook);
        rlBuyBook.setOnClickListener(this);
        rl_offline = (RelativeLayout) rootView.findViewById(R.id.rela_homebookshelf_offline);
        rl_offline.setOnClickListener(this);
        rl_rss = (RelativeLayout) rootView.findViewById(R.id.rela_homebookshelf_rss);
        rl_rss.setOnClickListener(this);
        tv_rss = (TextView) rootView.findViewById(R.id.tv_homebookshelf_rssnum);
        rlHistoryView = (RelativeLayout) rootView.findViewById(R.id.rela_dfbookuu);
        gallery = (Gallery) rootView.findViewById(R.id.spine_homebookshelef);
        gallery.setUnselectedAlpha(1.0f);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.leftMargin = -(ScreenUtil.getScreenWidth(getActivity())* 5/8);
        gallery.setLayoutParams(params);
        gallery.setPadding(0,0,-(ScreenUtil.getScreenWidth(getActivity())* 5/8),0);
        dfbook_notice_layout =  rootView.findViewById(R.id.dfbook_notice_layout);
        gallery.setOnItemClickListener(this);
        refreshLayout = rootView.findViewById(R.id.mRefreshLayout);
        refreshLayout.setOnRefreshListener(refreshlayout -> getDataFromNet());
        loadHistoryRecord();
        getScreenInfo();
        setSomeWidgetSize();
        ((WeMediaApplication) (WeMediaApplication.applicationContext)).isBookShelfReady = true;
        iconImag[0] = rootView.findViewById(R.id.iv_homebookshelf_keep);
        iconImag[1] = rootView.findViewById(R.id.iv_homebookshelf_history);
        iconImag[2] = rootView.findViewById(R.id.ivBuyBook);
        iconImag[3] = rootView.findViewById(R.id.iv_homebookshelf_offline);
        iconImag[4] = rootView.findViewById(R.id.iv_homebookshelf_rss);
        iconImag[5] = rootView.findViewById(R.id.ivBookList);
        layGift = rootView.findViewById(R.id.layGift);
        mScrollView = rootView.findViewById(R.id.mScrollView);
        laySign = rootView.findViewById(R.id.laySign);
        ivSign = rootView.findViewById(R.id.ivSign);
        tvSign = rootView.findViewById(R.id.tvSign);
        laySign.setOnClickListener(this);
    }


    private void setSomeWidgetSize() {
        //设置默认显示的宽高
        ViewGroup.LayoutParams params2 = rl_topHistoy.getLayoutParams();
        params2.height = (int) (scrrenWidth * 0.576 * 0.6 + DensityUtil.dip2px(getActivity(), 40));
        params2.width = ViewGroup.LayoutParams.MATCH_PARENT;
        rl_topHistoy.setLayoutParams(params2);
        {//set the centern
            LinearLayout.LayoutParams ViewParams = (LinearLayout.LayoutParams) rlHistoryView.getLayoutParams();
            if ((readRecordList != null) && (1 == readRecordList.size())) {
                ViewParams.leftMargin = 0;
            } else {
                ViewParams.leftMargin = 0;
            }
            rlHistoryView.setLayoutParams(ViewParams);
        }
    }

    private void setNewUserGift(NewUserGiftModel model) {
        if (model != null) {
            ChoiceTopicNewUserView view = new ChoiceTopicNewUserView(getActivity(), model, R.layout.view_new_user_gift_2);
            layGift.addView(view);
            layGift.setVisibility(View.VISIBLE);
            mScrollView.setPadding(0,0,0,ScreenUtil.dip2px(getActivity(),58));
        }else{
            layGift.setVisibility(View.GONE);
            mScrollView.setPadding(0,0,0,0);
        }
    }


    private List<ReadRecord> readRecordList = new ArrayList<>();

    public void loadHistoryRecord() {
        try {
            ReadHistoryUtil.getBookshelfData(getActivity(),new ReadHistoryUtil.OnGetDataResult() {
                @Override
                public void onNext(List<ReadRecord> list) {
                    readRecordList = list;
                    if ((readRecordList != null) && (readRecordList.size() > 0) || popularizeList.size() > 0) {
                        gallery.setVisibility(View.VISIBLE);
                        if (adapter == null) {
                            adapter = new BookshelfGalleryAdapter(getActivity(), popularizeList, readRecordList);
                            gallery.setAdapter(adapter);
                        } else {
                            adapter.updateReadRecordList(readRecordList);
                        }
                        rl_topHistoy.setVisibility(View.INVISIBLE);
                    } else {
                        gallery.setVisibility(View.INVISIBLE);
                        rl_topHistoy.setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void onError(Throwable e) {
                    try {
                        if ((readRecordList != null) && (readRecordList.size() > 0) || popularizeList.size() > 0) {
                            rl_topHistoy.setVisibility(View.INVISIBLE);
                            gallery.setVisibility(View.VISIBLE);
                        } else {
                            gallery.setVisibility(View.INVISIBLE);
                            rl_topHistoy.setVisibility(View.VISIBLE);
                        }
                    } catch (Exception e1) {

                    }

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getSignInfo() {
        String url = "http://api.doufu.la/member/signature";
        TFHttpUtil.requestGet(url, null, new TFHttpResponse() {
            @Override
            public void onResponse(com.alibaba.fastjson.JSONObject json, TFHttpError error) {
                try {
                    com.alibaba.fastjson.JSONObject data = json.getJSONObject("data");
                    if (data != null && data.getBoolean("signatured")) {
                        isSign = true;
                    }else{
                        isSign = false;
                    }
                    setSignView();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void setSignView() {
        if (isSign){
            tvSign.setText("已签");
            laySign.setAlpha(0.6f);
        }else{
            tvSign.setText("签到");
            laySign.setAlpha(1f);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.laySign:
                if (AccountService.getInstance().isLogin()) {
                    TMAnalysis.event(getActivity(), UmengEventName.BOOKSHELF_SIGN);
                    BrowseActivity.startActivity(getContext(),"https://api.doufu.la/signature");
                } else {
                    AccountService.getInstance().jumpToLogin();
                }
                break;
            case R.id.rela_homebookshelf_keep:
                if (AccountService.getInstance().isLogin()) {
                    SimpleWeexActivity.startActivity(getContext(),"/vue/collect/MyCollectPage.js");
                    TMAnalysis.event(getActivity(), "3_7_bookshelf_Collection");
                } else {
                    AccountService.getInstance().jumpToLogin();
                }

                break;
            case R.id.rela_homebookshelf_history:
                if (AccountService.getInstance().isLogin()) {
                    new StartActivityUtils(getActivity(), null).toHistoryActivity();
                    TMAnalysis.event(getActivity(), "3_7_bookshelf_Recentreading");
                } else {
                    AccountService.getInstance().jumpToLogin();
                }

                break;
            case R.id.rlBuyBook:
                if (AccountService.getInstance().isLogin()) {
                    new StartActivityUtils(getActivity(), null).toMyBuyBookActivity();
                    TMAnalysis.event(getActivity(), "Bookshelf_Buy_List");
                } else {
                    AccountService.getInstance().jumpToLogin();
                }
                break;
            case R.id.rela_homebookshelf_offline:
                if (AccountService.getInstance().isLogin()) {
                    new StartActivityUtils(getActivity(), null).toOfflineActivity();
                    TMAnalysis.event(getActivity(), "3_7_bookshelf_Offline");
                } else {
                    AccountService.getInstance().jumpToLogin();
                }
                break;
            case R.id.rlBookList:
                if (AccountService.getInstance().isLogin()) {
                    SimpleWeexActivity.startActivity(getActivity(),"vue/booklist/TFMyBookList.js");
                    TMAnalysis.event(getActivity(), "Bookshelf_BookList");
                } else {
                    AccountService.getInstance().jumpToLogin();
                }
                break;
            case R.id.rela_homebookshelf_rss:
                if (AccountService.getInstance().isLogin()) {
                    new StartActivityUtils(getActivity(), null).toRssActivity();
                    TMAnalysis.event(getActivity(), "3_7_bookshelf_Subscribe");
                } else {
                    AccountService.getInstance().jumpToLogin();
                }

                break;
            default:
                break;
        }
    }

    private void getDataFromNet() {
        HomeMainServices.getInstance().getBookshelfPopularize(this);
        HomeMainServices.getInstance().getHomeBookShelfBanner(this);
        HomeMainServices.getInstance().getHomeBookShelfMarket(this);
        loadHistoryRecord();
    }

    private void setData(BookShelfBean bean) {
        if ((bean != null) && (bean.getCount() != null) && (bean.getCount().length() > 0) && (!"0".equals(bean.getCount()))) {
            tv_rss.setVisibility(View.VISIBLE);
            tv_rss.setText(bean.getCount());
        } else {
            tv_rss.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void handleResponse(int handleType, final HttpResponseObject response) {
        switch (handleType) {
            case HomeMainServices.HANDLE_TYPE_BOOKSELF_POPULARIZE:
                if (response.getStatus() == Constant.STATUS_SUCCESS) {
                    try {
                        JSONObject obj = (JSONObject) response.getData();
                        BookShelfPopularizeList bspl = JSON.parseObject(obj.toString(), BookShelfPopularizeList.class);
                        if (bspl.getList() != null) {
                            popularizeList.clear();
                            popularizeList.addAll(bspl.getList());
                        }
                        setNewUserGift(bspl.getNew_user_pack());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    boolean showRecommend = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean("sp_personal_recommend", getContext(), true);
                    if (!showRecommend) {
                        popularizeList.clear();
                    }
                    if (adapter == null) {
                        adapter = new BookshelfGalleryAdapter(getActivity(), popularizeList, readRecordList);
                        gallery.setAdapter(adapter);
                    } else {
                        adapter.notifyDataSetChanged();
                    }
                    if ((readRecordList != null) && (readRecordList.size() > 0) || popularizeList.size() > 0) {
                        gallery.setVisibility(View.VISIBLE);
                        rl_topHistoy.setVisibility(View.INVISIBLE);
                    } else {
                        gallery.setVisibility(View.INVISIBLE);
                        rl_topHistoy.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (adapter == null) {
                        adapter = new BookshelfGalleryAdapter(getActivity(), popularizeList, readRecordList);
                        gallery.setAdapter(adapter);
                    } else {
                        adapter.notifyDataSetChanged();
                    }
                }
                refreshLayout.finishRefresh();
                break;
            case HomeMainServices.HANDLE_TYPE_HOMENOVELBOOKSELF:
                if (response.getStatus() == Constant.STATUS_SUCCESS) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            CacheUtil.saveJsonDataToCache(response.getData().toString(), new File(CommmonImp.Home_bookshelf));
                        }
                    }).start();
                    BookShelfBean bean = new BookShelfBean();
                    bean.setCount("0");
                    try {
                        JSONObject obj = (JSONObject) response.getData();
                        if ((obj.has("count"))) {
                            bean.setCount(obj.getString("count"));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    setData(bean);
                }
                break;
            case HomeMainServices.HANDLE_TYPE_HOMENOVELBOOKSELFMARKET://获取书架推广内容
                if (response.getStatus() == Constant.STATUS_SUCCESS) {
                    try {
                        JSONObject obj = (JSONObject) response.getData();
                        if (obj.has("list")) {
                            marketNoticeList = com.alibaba.fastjson.JSONArray.parseArray(obj.getJSONArray("list").toString(), MarketNoticeBean.class);
                            //数据缓存
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    CacheUtil.saveJsonDataToCache(response.getData().toString(), new File(CommmonImp.Home_bookshelf_market));
                                }
                            }).start();

                            if ((marketNoticeList != null) && (marketNoticeList.size() > 0)) {
                                if (TextUtils.isEmpty(marketNoticeList.get(0).getMsg())) {
                                    autoScrollView.setVisibility(View.GONE);
                                    dfbook_notice_layout.setVisibility(View.GONE);
                                } else {
                                    autoScrollView.updateScroolNotices(tvLeftTag, marketNoticeList);
                                    autoScrollView.setVisibility(View.VISIBLE);
                                    dfbook_notice_layout.setVisibility(View.VISIBLE);
                                }
                            } else {
                                autoScrollView.setVisibility(View.GONE);
                                dfbook_notice_layout.setVisibility(View.GONE);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        UIUtil.toastMessage(getActivity(), Constant.loadingFail);
                    }
                }
                break;
        }
    }

    private int scrrenWidth = 0;

    private void getScreenInfo() {
        DisplayMetrics dpMetrics = new DisplayMetrics();
        getActivity().getWindow().getWindowManager().getDefaultDisplay()
                .getMetrics(dpMetrics);
        scrrenWidth = dpMetrics.widthPixels;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (popularizeList.size() > 0 && position < popularizeList.size()) {
            TMAnalysis.event(getActivity(), "3_8_bookshelfSliding_AD");
            try{
                int object_type = Integer.parseInt(popularizeList.get(position).getObject_type());
                int object_id = Integer.parseInt(popularizeList.get(position).getId());
                String url = popularizeList.get(position).getData();
                String title = popularizeList.get(position).getTitle();
                Intent intent = new Intent();
                if (object_type == ContentType.CONTENT_TYPE_NOVEL) {
                    UserLogManager.addLog(UserLogManager.LOG_EVENT_NAME_NOVEL_DETAIL,String.valueOf(object_id),"","书架","TFNovelDetail.js");
                    NovelDetailsActivity.Companion.startActivity(getActivity(),object_id,Intent.FLAG_ACTIVITY_NEW_TASK);
                } else if (object_type == ContentType.CONTENT_TYPE_CARTOON) {
                    intent.putExtra(Constant.CARTOON_ID, String.valueOf(object_id));
                    new StartActivityUtils(getActivity(), intent).toCartoonDesActivity(String.valueOf(object_id));
                } else if (object_type == ContentType.CONTENT_TYPE_NOMAL) {
                    PersonalNoteService.getInstance().enterPersonalNoteDesActivity(getActivity(), String.valueOf(object_id), String.valueOf(object_type));
                } else if (!TextUtils.isEmpty(url)) {
                    intent.setClass(getActivity(), BrowseActivity.class);
                    intent.putExtra(Constant.URL, popularizeList.get(position).getData());
                    intent.putExtra(Constant.TITLE, popularizeList.get(position).getTitle());
                    startActivity(intent);
                }
            }catch (Exception e){
                Intent intent = new Intent();
                intent.setClass(getActivity(), BrowseActivity.class);
                intent.putExtra(Constant.URL, popularizeList.get(position).getData());
                intent.putExtra(Constant.TITLE, popularizeList.get(position).getTitle());
                startActivity(intent);
            }
        } else if (readRecordList != null && readRecordList.get(position - popularizeList.size()) != null) {
            TMAnalysis.event(getActivity(), "3_7_bookshelf_Sliding");
            ReadRecord hisReadRecord = readRecordList.get(position - popularizeList.size());
            if (hisReadRecord.getType() ==  Constant.OBJECT_TYPE_CARTOON) {

                if (hisReadRecord.getJump_type() == BookshelfJumpType.TYPE_JUMP_TO_DETAL) {
                    CartoonServices.enterCartoonDes(getActivity(), hisReadRecord.getNovel_id());
                }else{
                    //漫画
                    Intent intent = new Intent(getActivity(), CartoonScanNewActivity.class);
                    intent.putExtra(Constant.CARTOON_ID, hisReadRecord.getNovel_id());
                    startActivity(intent);
                }

            } else {
                //小说
                if (hisReadRecord.getJump_type() == BookshelfJumpType.TYPE_JUMP_TO_DETAL) {
                    StartActivityUtil.novelOnclick(getActivity(), hisReadRecord.getNovel_id());
                }else{
                    Intent intent = new Intent(getActivity(), NovelSectionDetailsActivity.class);
                    intent.putExtra(Constant.ARTICLE_ID, hisReadRecord.getSection_id());
                    intent.putExtra(Constant.ARTICLE_NOVELID, hisReadRecord.getNovel_id());
                    intent.putExtra(Constant.IS_SELF, true);
                    startActivityForResult(intent, 777);
                }
            }
        }
    }

    /**
     * 切换主题
     */
    public void changeThemeWithColorful() {
        if (WeMediaApplication.getInstance().isDayNightMode_Night) {
            mColorful.setTheme(R.style.theme_dark);
            tvLeftTag.setBackground(getResources().getDrawable(R.drawable.shape_roundrectangle_dfbook_dark_2));
        } else {
            mColorful.setTheme(R.style.theme_day);
            tvLeftTag.setBackground(getResources().getDrawable(R.drawable.shape_roundrectangle_2));
        }
        changeIconBg();

    }
    private void setupColorful(){
        // 构建Colorful对象来绑定View与属性的对象关系
        mColorful = new Colorful.Builder(getActivity())
                .backgroundDrawable(R.id.dfbook_shelf_rootLayout, R.attr.foreground_bg)
                // 设置view的背景图片
                .backgroundColor(R.id.dfbook_shelf_head_title_layout, R.attr.foreground_bg)
                .backgroundColor(R.id.dfbook_shelf_item_layout, R.attr.foreground_bg)
                //设置线的颜色
                .backgroundColor(R.id.iv_homebookshelf_keep_line, R.attr.home_line_corol)
                .backgroundColor(R.id.line_homebookshelf_book_list, R.attr.home_line_corol)
                .backgroundColor(R.id.line_homebookshelf_book_list_2, R.attr.home_line_corol)
                .backgroundColor(R.id.lineBuyBook, R.attr.home_line_corol)
                .backgroundColor(R.id.line_homebookshelf_offline, R.attr.home_line_corol)
                .backgroundColor(R.id.line_homebookshelf_history, R.attr.home_line_corol)
                .backgroundColor(R.id.line_homebookshelf_rssback, R.attr.home_line_corol)
                .backgroundDrawable(R.id.tv_homebookshelf_rssnum, R.attr.circle_gray_bg)
                .backgroundDrawable(R.id.tvUnRead, R.attr.cycle_red)
                // 设置字体景色
                .textColor(R.id.dfbook_shelf_title_tv, R.attr.top_title_text_color)
                .textColor(R.id.tv_homebookshelf_keep, R.attr.text_color_6)
                .textColor(R.id.tvBookList, R.attr.text_color_6)
                .textColor(R.id.tv_homebookshelf_history, R.attr.text_color_6)
                .textColor(R.id.tvBuyBook, R.attr.text_color_6)
                .textColor(R.id.tv_homebookshelf_offline, R.attr.text_color_6)
                .textColor(R.id.tv_homebookshelf_rss, R.attr.text_color_6)
                .textColor(R.id.tv_homebookshelf_rssnum, R.attr.text_color_34)
                .textColor(R.id.tvUnRead, R.attr.top_title_text_while_color)
                .imagResourc(R.id.homebookshelf_keep_arrow, R.attr.personal_center_arrow)
                .imagResourc(R.id.ivBookListArrow, R.attr.personal_center_arrow)
                .imagResourc(R.id.homebookshelf_history_arrow, R.attr.personal_center_arrow)
                .imagResourc(R.id.ivBuyBookArrow, R.attr.personal_center_arrow)
                .imagResourc(R.id.homebookshelf_offline_arrow, R.attr.personal_center_arrow)
                .imagResourc(R.id.homebookshelf_rssback_arrow, R.attr.personal_center_arrow)
                .backgroundColor(R.id.dfbook_notice_layout, R.attr.shape_roundrectangle_dfbook_2)
                .backgroundColor(R.id.tv_home_type, R.attr.cycle_red)
//                .setter(listViewSetter) // 手动设置setter
                .create(); // 设置文本颜色
    }

    private void  changeIconBg(){
        for(int i = 0 ;i < iconImag.length; i++){
            if(WeMediaApplication.getInstance().isDayNightMode_Night){
                iconImag[i].setAlpha(0.5f);
                iconImag[i].setBackgroundColor(getResources().getColor(R.color.fg_dark));
            }else {
                iconImag[i].setAlpha(1.0f);
                iconImag[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
            }
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        getCollectUnRead(getActivity());
        getSignInfo();
    }

    /**
     * 获取收藏作品的未读数
     */
    public static void getCollectUnRead(Activity activity) {
        ApiClient.getInstance().setUseCache(false).getService().getCollectUnRead()
                .compose(RxJavaHelper.<CollectUnReadBean>observeOnMainThread(activity))
                .subscribe(new BaseSubscriber<CollectUnReadBean>(){
                    @Override
                    public void onNext(CollectUnReadBean collectUnReadBean) {
                        super.onNext(collectUnReadBean);
                        if (collectUnReadBean!=null &&
                                collectUnReadBean.getData()!=null){
                            EventBusCollectUnRead event = new EventBusCollectUnRead();
                            event.setTag(EventBusCollectUnRead.TAG_BOOK_SHELF);
                            if (!TextUtils.isEmpty(collectUnReadBean.getData().getTip())){
                                event.setShow(true);
                                event.setShowText(collectUnReadBean.getData().getTip());
                            }else{
                                event.setShow(false);
                            }
                            EventBus.getDefault().post(event);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }
}
